#!/usr/bin/env python

__author__ = "Abhinav Sarkar"
__version__ = "0.1"
__license__ = "GNU Lesser General Public License"

class Event (object):
	"""A class representing an event.
	
	The Event class exposes the following instance properties:
		
		event.id
		event.url
		event.start
		event.end
		event.summary
		event.description
		event.venue
		event.venueUrl
		event.country
		
	The Event class exposes the following instance methods:
	
		event.AsDict()
	"""
	def __init__(self,
				 id = None,
				 url = None,
				 start = None,
				 end = None,
				 summary = None,
				 description = None,
				 venue = None,
				 venueUrl = None,
				 country = None):
		"""An object to hold an Event.
		
		This class is normally instantiated by the User and Artist classes.
		
		Args:
			id: unique ID of this event as assigned by last.fm
			url: URL of this event on last.fm
			start:
				a datetime.datetime object corresponding to the start time
				of this event
			end:
				a datetime.datetime object corresponding to the end time
				of this event
			summary: summary of this event
			description: description of this event
			venue: venue of this event
			venueUrl: URL of the venue of this event, on last.fm
			country:
				a Country object corresponding to the country of the venue of
				this event 
		"""
		self.id = id
		self.url = url
		self.start = start
		self.end = end
		self.summary = summary
		self.description = description
		self.venue = venue
		self.venueUrl = venueUrl
		self.country = country

	@staticmethod
	def fromICal(url):
		"""Static method to create an Events list from a given ICal URL.
		
		Do not call this method. Its called by the Webservice class.
		
		Returns:
			A list of Event objects created from the data in given ICal URL. 
		"""
		try:
			iCalText = Webservice()._FetchUrl(url)
		except urllib2.HTTPError,e:
			if e.code == 404:
				raise AudioscrobblerError("Track does not exist")
					
		events = []
		nodes = vobject.readComponents(StringIO.StringIO(iCalText)).next().getChildren()
		for node in nodes:
			try:
				events.append(
					Event(
						id = node.uid.value,
						url = node.url.value,
						start = node.dtstart.value,
						end = node.dtend.value,
						summary = node.summary.value,
						description = node.description.value,
						venue = node.location.value,
						venueUrl = node.location.params['VENUE-UID'][0],
						country = Country(node.location.value.split(', ')[-1])
					)
				)
			except AttributeError:
				pass
			
		return events
		
		
	def AsDict(self):
		"""Return self as a dict."""
		return self.__dict__

	def __eq__(self, other):
		return self.id == other.id

	def __ne__(self, other):
		return not self.__eq__(other)
	
import vobject
import urllib2
import cStringIO as StringIO

from webservice import Webservice
from error import AudioscrobblerError
from country import Country